﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Http;
using System.Collections.Concurrent;
using System.IO;
using System.Net.Http;
using System.Net;

namespace ERPStore.Web.Controllers
{
	public class PushLogController : ApiController
	{
		private static readonly ConcurrentDictionary<StreamWriter, StreamWriter> _outputs = new ConcurrentDictionary<StreamWriter, StreamWriter>();

		public HttpResponseMessage GetUpdates(HttpRequestMessage request)
		{
			var apiKeyHeader = request.Headers.FirstOrDefault(h => "apikey".Equals(h.Key, StringComparison.InvariantCultureIgnoreCase));
			if (apiKeyHeader.Value == null)
			{
				var httpMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized);
				throw new HttpResponseException(httpMessage);
			}
			if (!apiKeyHeader.Value.First().Equals(ERPStore.GlobalConfiguration.Configuration.Settings.ApiToken))
			{
				var httpMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized);
				throw new HttpResponseException(httpMessage);
			}

			request.Headers.Clear();
			var response = request.CreateResponse();
			response.Content = new PushStreamContent(OnStreamAvailable, "text/plain");
			return response;
		}

		private void OnStreamAvailable(Stream stream, HttpContent content, TransportContext context)
		{
			var streamwriter = new StreamWriter(stream);
			_outputs.TryAdd(streamwriter, streamwriter);
		}

		public static void WriteLog(string message)
		{
			foreach (var kvp in _outputs.ToArray())
			{
				try
				{
					kvp.Value.Write(message);
					kvp.Value.Flush();
				}
				catch
				{
					StreamWriter sWriter;
					_outputs.TryRemove(kvp.Value, out sWriter);
				}
			}
		}

	}
}
